package com.markedquilt.SwordForOffer;
/*
 * PackageName: com.markedquilt.SwordForOffer
 * ClassName:
 * Author:   zhang
 * Date:     Created in 2020/11/13
 * Description:
 * History:
 * <author>        <time>             <version>          <desc>
 * 作者姓名         修改时间            版本号              描述
 * zhang           2020/11/13      1.0
 */

import com.markedquilt.SwordForOffer.entity.ListNode;

/**
 * Title:
 * Project: LeetcodeProblem
 *
 * @author ZhangKe
 * Created on 2020/11/13
 */
public class _getKthFromEnd22 {
    public static ListNode getKthFromEnd(ListNode head, int k) {
        ListNode end = head;
        if (k==0 || head == null){
            return null;
        }
        if (head.next==null){
            return head;
        }
        int length=0;
        while(end!=null){
            length++;
            end = end.next;
        }
        if (k>length){
            return null;
        }
        if (k == length){
            return head;
        }
        end =head;
        for (int i = 1; i < length-k+1; i++) {
            end = end.next;
        }
        return  end;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;
        ListNode node = getKthFromEnd(node1,2);
        while(node!=null){
            System.out.println(node.val);
            node = node.next;
        }
    }
}
